package com.sservice.common;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


public class HttpRequest {
    private static final Object HTTP = "";
    //private  static Logger logger = LoggerFactory.getLogger(HttpRequest.class);
    /**
     *  危化品查询链接
     */
    private static String DOMAIN = "http://media.chinasafety.gov.cn:8090/iSystem/dcproduct/result.jsp";

    public static String doGet(WhpcxQuery param) {
        String uriAPI = DOMAIN+"?type="+param.getType()+"&key="+param.getKey();//Post方式没有参数在这里
        String result = "";
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpPost = new HttpGet(uriAPI);
            httpPost.setHeader("Content-type", "application/json");

            HttpResponse httpResponse = httpClient.execute(httpPost);
            return getResult(httpResponse);
        } catch (Exception e) {
            e.printStackTrace();
            result = e.getMessage().toString();
        }
        return result;
    }


    private static String getResult(HttpResponse httpResponse) throws IOException {
        String result = "";
        if (httpResponse.getStatusLine().getStatusCode() == 200 || httpResponse.getStatusLine().getStatusCode() == 500) {
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);//取出应答字符串
            return result;
        }
        return result;
    }

    /***
     * chong
     * @return
     * @throws IOException
     */
    public static JSONObject reformatRes(String res) throws IOException {
        String result = "";
        if (res.indexOf("{") == 0) {
            return JSONObject.parseObject(res);
        }
        if (res.indexOf("[") == 0) {
            return JSONArray.parseObject(res);
        }
        return JSONObject.parseObject("{\"error\":\"" + res + "\"}");
    }

}

